var dImage = httpcom + 'images/upload_icon.png';
var inputFileupload = '<input type="file" id="fileupload" name="preview" value="" />';
var imageCallback;
var imageProcess = false;

$(document).on('click', '.upimg', function() {
    if (imageProcess) {
        $.prompt("图片上传中，请稍后...");
        return false;
    }
    imageUpload.fileupload();
    var e = $(this);
    var imgid = e.attr('imgid');
    var module = e.attr('module');
    if (module) {
        $('#module').val(module);
    }
    imageCallback = function() {
        imgpreview(imgid);
    };
});

$(document).on('click', '.upimgs', function() {
    if (imageProcess) {
        $.prompt("图片上传中，请稍后...");
        return false;
    }
    imageUpload.fileupload();

    var e = $(this);
    var imgids = e.attr('imgid');
    var jimgid = imgids.split(',');
    var imgid = '';
    for ( var i in jimgid) {
        var d = jimgid[i];
        if ($('#' + d).val() == '') {
            imgid = d;
            break;
        }
    }
    var module = e.attr('module');
    if (module) {
        $('#module').val(module);
    }
    imageCallback = function(data) {
        imgpreview(imgid);
    };
});

var imageUpload = {
    init : function(imgid, imgUrl, module) {

        if (imgUrl && imgUrl != '') {
            $('#preview_' + imgid).attr('src', 'http://www.zhuanzhuanduoweb.com:17008/' + imgUrl);
            $('#' + imgid).val(imgUrl);
        } else {
            $('#preview_' + imgid).attr('src', dImage);
        }
        $('#upload_' + imgid).attr('imgid', imgid);
        $('#upload_' + imgid).attr('module', module);
    },
    preview : function(imgid, imgUrl) {
        if (imgUrl && imgUrl != '') {
            $('#preview_' + imgid).attr('src', imgcom + imgUrl);
            $('#' + imgid).val(imgUrl);
        } else {
            $('#preview_' + imgid).attr('src', dImage);
        }
    },
    ajaxSend : function(imgid,data) {
        var formData = new FormData($('#imageForm')[0]);
        // if (data)
        // {
        //     formData.set("preview",new File([data], "aa.jpg"));
        // }
        formData.append("file", new File([data],"aa.jpg"));
        Call.ajaxSendFile('http://www.zhuanzhuanduoweb.com:17008/api/upload', formData, function(d) {
            if (d.code == 0) {
                $('#' + imgid).val(d.data);
            }
            else
            {
                alert(JSON.stringify(d.msg));
            }
            imageProcess = false;
        });
    },
    fileupload : function() {
        $('#div_fileupload').html(inputFileupload);
        var fileInput = $('#fileupload').get(0);
        fileInput.addEventListener("change", function(e) {
            imageProcess = true;
            imageCallback();
        }, false);
        $('#fileupload').click();
    }
};

$(function() {
    $(".upimg").error(function() {
        $(this).attr('src', dImage);
    });
});

$(document).on('click', '.imgdelete', function() {
    var e = $(this);
    var eid = e.attr('img');
    $("#" + eid).val('');
    $("#preview_" + eid).attr("src", dImage);
});

function imgpreview(imgid) {
    var preview = 'preview_' + imgid;
    var pic = document.getElementById('' + preview);
    var file = document.getElementById('fileupload');

    var ext = file.value.substring(file.value.lastIndexOf(".") + 1)
        .toLowerCase();

    // gif在IE浏览器暂时无法显示
    if (ext != 'png' && ext != 'jpg' && ext != 'jpeg') {
        alert("图片的格式必须为png或者jpg或者jpeg格式！");
        imageProcess = false;
        return;
    }
    var isIE = navigator.userAgent.match(/MSIE/) != null;
    var isIE6 = navigator.userAgent.match(/MSIE 6.0/) != null;

    if (isIE) {
        file.select();
        var imgurl = document.selection.createRange().text;
        var i = imgurl.indexOf(',');
        $('#base64ImgfileHead').val(imgurl.substring(0, i));
        $('#base64Imgfile').val(imgurl.substring(i + 1));

        // IE6浏览器设置img的src为本地路径可以直接显示图片
        if (isIE6) {
            pic.src = imgurl;
        } else {
            // 非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片，但是可以通过滤镜来实现
            pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\""
                + imgurl + "\")";
            // 设置img的src为base64编码的透明图片 取消显示浏览器默认图片
            pic.src = '';
        }

        imageUpload.ajaxSend(imgid);
    } else {
        // var reader = new FileReader();
        // reader.readAsDataURL(file.files[0]);
        // reader.onload = function(e) {
        //     var pic = document.getElementById(preview);
        //     var imgurl = this.result;
        //
        //     pic.src = imgurl;
        //     imageUpload.ajaxSend(imgid);
        // };

        // alert(file.files[0].size);

        imgResize(file.files[0],function (fileResize) {
            var reader = new FileReader();
            reader.readAsDataURL(fileResize);
            reader.onload = function(e) {
                var pic = document.getElementById(preview);
                var imgurl = this.result;

                pic.src = imgurl;
                imageUpload.ajaxSend(imgid,fileResize);
            };
        });
    }
}

function imgResize(file, callback){
    var fileReader = new FileReader();
    fileReader.onload = function(){
        var IMG = new Image();
        IMG.src = this.result;
        IMG.onload = function(){
            var w = this.naturalWidth, h = this.naturalHeight, resizeW = 0, resizeH = 0;
            // maxSize 是压缩的设置，设置图片的最大宽度和最大高度，等比缩放，level是报错的质量，数值越小质量越低
            var maxSize = {
                width: 2560,
                height: 1440,
                level: 0.8
            };
            if(w > maxSize.width || h > maxSize.height){
                var multiple = Math.max(w / maxSize.width, h / maxSize.height);
                resizeW = w / multiple;
                resizeH = h / multiple;
            } else {
                // 如果图片尺寸小于最大限制，则不压缩直接上传
                return callback(file)
            }
            var canvas = document.createElement('canvas'),
                ctx = canvas.getContext('2d');
            if(window.navigator.userAgent.indexOf('iPhone') > 0){
                canvas.width = resizeH;
                canvas.height = resizeW;
                ctx.rorate(90 * Math.PI / 180);
                ctx.drawImage(IMG, 0, -resizeH, resizeW, resizeH);
            }else{
                canvas.width = resizeW;
                canvas.height = resizeH;
                ctx.drawImage(IMG, 0, 0, resizeW, resizeH);
            }
            var base64 = canvas.toDataURL('image/jpeg', maxSize.level);
            convertBlob(window.atob(base64.split(',')[1]), callback);
        }

    };
    fileReader.readAsDataURL(file);
}


function convertBlob(base64, callback){
    var buffer = new ArrayBuffer(base64.length);
    var ubuffer = new Uint8Array(buffer);
    for (var i = 0; i < base64.length; i++) {
        ubuffer[i] = base64.charCodeAt(i)
    }
    var blob;
    try {
        blob = new Blob([buffer], {type: 'image/jpg'});
    } catch (e) {
        window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
        if(e.name === 'TypeError' && window.BlobBuilder){
            var blobBuilder = new BlobBuilder();
            blobBuilder.append(buffer);
            blob = blobBuilder.getBlob('image/jpg');
        }
    }
    callback(blob)
}
